package main;

import java.awt.event.KeyEvent;
import java.util.Arrays;
import java.util.HashMap;
import java.util.LinkedList;
import java.util.List;

public class Snake {
	private HashMap<Integer, int[]> dirMap = new HashMap<Integer, int[]>() {
		{
			put(KeyEvent.VK_UP, new int[] { 0, -1 });
			put(KeyEvent.VK_DOWN, new int[] { 0, 1 });
			put(KeyEvent.VK_LEFT, new int[] { -1, 0 });
			put(KeyEvent.VK_RIGHT, new int[] { 1, 0 });
		}
	};
	private int[] dir = dirMap.get(KeyEvent.VK_UP);
	private List<int[]> snakeNodes = new LinkedList<int[]>();
	private Boolean status;

	public void setStatus(Boolean status) {
		this.status = status;
	}

	public Boolean getStatus() {
		return status;
	}

	public Snake(int[] initPosition) {
		this.snakeNodes.add(initPosition);
		this.status = true;
	}

	public void changeDir(Integer keycode) {
		// 不能向后移动
		if (!(dirMap.get(keycode)[0] == -this.dir[0] && dirMap.get(keycode)[1] == -this.dir[1])) {
			this.dir = dirMap.get(keycode);
		}
	}

	private int[] getHead() {
		return this.snakeNodes.get(0);
	}

	public List<int[]> getNodes() {
		return this.snakeNodes;
	}

	public void grow() {
		// 这里是为了让crawl删除时有一个垫数的
		this.snakeNodes.add(new int[] { -1, -1 });
	}

	public void crawl() {
		// 撞到自己的判定
		int[] head = snakeNodes.get(0);
		for (int[] e : snakeNodes) {
			if (e == head) {
				continue;
			}
			if (Arrays.equals(head, e)) {
				System.out.println("撞到自己");
			}
		}
		head = new int[] { this.getHead()[0] + this.dir[0], this.getHead()[1] + this.dir[1] };
		snakeNodes.add(0, head);
		snakeNodes.remove(snakeNodes.size() - 1);
	}

	public int length() {
		return snakeNodes.size();
	}
}